// Modal.vue
<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onOkButtonClick"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, toRaw, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { setDutyModalSchemas } from './responsibility.data';
  import { getOrgDeptTree } from '/@/api/ehs/organization';
  import { getDeptUsers } from '/@/api/public/public';
  import { useGlobSetting } from '/@/hooks/setting';
  import { setUnitResponsibility } from '/@/api/ehs/responsibility';
  import { getUserOrganization, getOrganization } from '/@/api/ehs/organization';
  const { globalProjectCode } = useGlobSetting();
  const { createMessage } = useMessage();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    name: 'setUnitResponsibilityModal',
    emits: ['success'],
    setup(props, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const deptData = ref([]);
      const userData = ref([]);
      const orgcode = ref('');
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: setDutyModalSchemas,
        showActionButtonGroup: false,
        scrollToFirstError: true,
        actionColOptions: {
          span: 24,
        },
      });
      const [register, { closeModal }] = useModalInner((data) => {
        resetFields();
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          getOrgDeptTree(orgcode.value).then((res1) => {
            deptData.value = res1;
            updateSchema([
              {
                field: 'unitids',
                componentProps: {
                  treeData: unrefData.unitData,
                  treeCheckStrictly: true,
                  mode: 'tags',
                  listHeight: 250,
                  getPopupContainer: (triggerNode) => document.body,
                  fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                  treeDefaultExpandAll: true,
                  treeCheckable: true, //	显示checkbox，多选
                  showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
                },
              },
              {
                field: 'resdeptid',
                componentProps: {
                  onChange: (value) => {
                    getDeptUsers(value).then((res) => {
                      updateSchema([
                        {
                          field: 'resuserid',
                          componentProps: ({ formModel }) => {
                            return {
                              options: res,
                              onChange: (value) => {
                                formModel.resuserphone = res.find(
                                  (item) => item.id === value,
                                )?.phone;
                              },
                              listHeight: 220,
                              getPopupContainer: (triggerNode) => document.body,
                              fieldNames: { label: 'name', value: 'id' },
                            };
                          },
                        },
                        {
                          field: 'safeuserid',
                          componentProps: ({ formModel, formActionType }) => {
                            return {
                              onChange: (value) => {
                                formModel.safeuserphone = res.find(
                                  (item) => item.id === value,
                                )?.phone;
                              },
                              listHeight: 220,
                              options: res,
                              getPopupContainer: (triggerNode) => document.body,
                              fieldNames: { label: 'name', value: 'id', phone: 'phone' },
                            };
                          },
                        },
                      ]);
                    });
                    setFieldsValue({
                      resuserid: null,
                      safeuserid: null,
                    });
                  },
                  treeData: res1,
                  treeDefaultExpandAll: true, //默认展开
                  listHeight: 220,
                  getPopupContainer: (triggerNode) => document.body,
                  fieldNames: { label: 'title', value: 'key', children: 'children' },
                },
              },
            ]);
          });
          if (unrefData?.ids) {
            setFieldsValue({
              unitids: unrefData?.ids,
              resdeptid:
                unrefData.defaultData.resdeptid > 0 ? unrefData.defaultData.resdeptid : null,
              resuserid:
                unrefData.defaultData.resuserid > 0 ? unrefData.defaultData.resuserid : null,
              safeuserid:
                unrefData.defaultData.safeuserid > 0 ? unrefData.defaultData.safeuserid : null,
              resuserphone: unrefData.defaultData.resuserphone ?? null,
              safeuserphone: unrefData.defaultData.safeuserphone ?? null,
            });
            if (unrefData.defaultData.resdeptid > 0)
              getDeptUsers(unrefData.defaultData.resdeptid).then((res) => {
                updateSchema([
                  {
                    field: 'resuserid',
                    componentProps: ({ formModel }) => {
                      return {
                        options: res,
                        onChange: (value) => {
                          formModel.resuserphone = res.find((item) => item.id === value)?.phone;
                        },
                        listHeight: 220,
                        getPopupContainer: (triggerNode) => document.body,
                        fieldNames: { label: 'name', value: 'id' },
                      };
                    },
                  },
                  {
                    field: 'safeuserid',
                    componentProps: ({ formModel, formActionType }) => {
                      return {
                        onChange: (value) => {
                          formModel.safeuserphone = res.find((item) => item.id === value)?.phone;
                        },
                        listHeight: 220,
                        options: res,
                        getPopupContainer: (triggerNode) => document.body,
                        fieldNames: { label: 'name', value: 'id', phone: 'phone' },
                      };
                    },
                  },
                ]);
              });
          }
        }
      });

      async function onOkButtonClick() {
        let values = await validate();
        let userData = [];
        console.log(treeToArray(deptData.value), '121212');
        getDeptUsers(values.resdeptid).then((res) => {
          userData = res;
          let params = {
            unitids: toRaw(values.unitids),
            resdeptid: values.resdeptid,
            resdeptname: treeToArray(deptData.value).find((item) => item.key == values.resdeptid)
              ?.title,
            resuserid: values.resuserid,
            resusername: userData.find((item) => item.id == values.resuserid)?.name,
            resuserphone: values.resuserphone,
            safeuserid: values.safeuserid,
            safeusername: userData.find((item) => item.id == values.safeuserid)?.name,
            safeuserphone: values.safeuserphone,
          };
          console.log(params);
          setUnitResponsibility(params).then((res) => {
            if (!res) {
              closeModal();
              emit('success');
            }
          });
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      onMounted(() => {
        getUserOrganization(globalProjectCode).then((res) => {
          orgcode.value = res.orgcode;
        });
      });

      return {
        register,
        registerForm,
        closeModal,
        displayModuleTitle,
        onOkButtonClick,
      };
    },
  });
</script>
